'''
Author: bodhi
Date: 2025-01-09
LastEditors: bodhi
LastEditTime: 2025-01-09
FilePath: wordproc/src/utils/excel_recorder.py
'''
import pandas as pd
from pathlib import Path
from typing import Dict, List, Optional
import logging
from datetime import datetime


class ExcelRecorder:
    """Excel评分结果记录器"""
    
    def __init__(self, output_dir: Path, logger: Optional[logging.Logger] = None):
        """
        初始化Excel记录器
        
        Args:
            output_dir: 输出目录路径
            logger: 日志记录器
        """
        self.output_dir = output_dir
        self.logger = logger
        self.excel_file = output_dir / f"评分结果_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        self.results = []
        
        if self.logger:
            self.logger.info(f"Excel记录器初始化完成，输出文件: {self.excel_file}")
    
    def add_result(self, student_id: str, student_name: str, score: int, comments: str = ""):
        """
        添加一个评分结果
        
        Args:
            student_id: 学号
            student_name: 姓名
            score: 成绩
            comments: 评语（可选）
        """
        result = {
            '学号': student_id,
            '姓名': student_name,
            '成绩': score,
            '评语': comments,
            '评分时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        self.results.append(result)
        
        if self.logger:
            self.logger.info(f"添加评分结果: {student_id} - {student_name} - {score}分")
    
    def save_to_excel(self):
        """
        将所有评分结果保存到Excel文件
        """
        if not self.results:
            if self.logger:
                self.logger.warning("没有评分结果需要保存")
            return
        
        try:
            # 创建DataFrame
            df = pd.DataFrame(self.results)
            
            # 按学号排序
            df = df.sort_values('学号')
            
            # 保存到Excel文件
            with pd.ExcelWriter(self.excel_file, engine='openpyxl') as writer:
                df.to_excel(writer, sheet_name='评分结果', index=False)
                
                # 获取工作表对象以进行格式设置
                worksheet = writer.sheets['评分结果']
                
                # 设置列宽
                worksheet.column_dimensions['A'].width = 15  # 学号
                worksheet.column_dimensions['B'].width = 10  # 姓名
                worksheet.column_dimensions['C'].width = 8   # 成绩
                worksheet.column_dimensions['D'].width = 50  # 评语
                worksheet.column_dimensions['E'].width = 20  # 评分时间
            
            if self.logger:
                self.logger.info(f"评分结果已保存到Excel文件: {self.excel_file}")
                self.logger.info(f"共记录 {len(self.results)} 个学生的评分结果")
                
        except Exception as e:
            if self.logger:
                self.logger.error(f"保存Excel文件时发生错误: {str(e)}")
            raise
    
    def get_statistics(self) -> Dict[str, any]:
        """
        获取评分统计信息
        
        Returns:
            包含统计信息的字典
        """
        if not self.results:
            return {
                'total_students': 0,
                'average_score': 0,
                'highest_score': 0,
                'lowest_score': 0,
                'score_distribution': {}
            }
        
        scores = [result['成绩'] for result in self.results]
        
        # 计算分数分布
        score_distribution = {}
        for score in scores:
            score_range = f"{(score // 10) * 10}-{(score // 10) * 10 + 9}"
            score_distribution[score_range] = score_distribution.get(score_range, 0) + 1
        
        return {
            'total_students': len(self.results),
            'average_score': round(sum(scores) / len(scores), 2),
            'highest_score': max(scores),
            'lowest_score': min(scores),
            'score_distribution': score_distribution
        } 